package com.lrkj.payfee.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lrkj.common.constant.FeeConstants;
import com.lrkj.common.constant.OrgConstants;
import com.lrkj.common.utils.DateUtils;
import com.lrkj.common.utils.NumberArithmeticUtils;
import com.lrkj.common.utils.SecurityUtils;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.framework.security.MiniContextUtils;
import com.lrkj.framework.utils.NumberUtils;
import com.lrkj.framework.utils.SerialNumUtil;
import com.lrkj.payfee.domain.BalanceRefill;
import com.lrkj.payfee.domain.RoomBalance;
import com.lrkj.payfee.mapper.BalanceRefillMapper;
import com.lrkj.payfee.service.IBalanceRefillService;
import com.lrkj.payfee.service.IRoomBalanceService;
import com.lrkj.payfee.service.IWxPayfeeService;
import com.lrkj.payfee.vo.BillPaymentVo;
import com.lrkj.payfee.vo.BillVo;
import com.lrkj.payfee.vo.PayBalanceRefillVo;
import com.lrkj.property.domain.Room;
import com.lrkj.property.service.IRoomService;
import com.lrkj.system.service.IOrgTreeService;
import com.lrkj.waitress.domain.CustomInfo;
import com.lrkj.waitress.service.ICustomInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 余额充值Service业务层处理
 *
 * @author yajun_ren
 * @date 2022-07-25
 */
@Service
public class BalanceRefillServiceImpl implements IBalanceRefillService {
    @Autowired
    private BalanceRefillMapper balanceRefillMapper;

    @Autowired
    private ICustomInfoService customInfoService;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private IOrgTreeService orgTreeService;

    @Autowired
    private IRoomBalanceService roomBalanceService;

    @Autowired
    private IWxPayfeeService wxPayfeeService;

    /**
     * 查询余额充值
     *
     * @param id 余额充值ID
     * @return 余额充值
     */
    @Override
    public BalanceRefill selectBalanceRefillById(String id) {
        return balanceRefillMapper.selectBalanceRefillById(id);
    }

    /**
     * 查询余额充值列表
     *
     * @param balanceRefill 余额充值
     * @return 余额充值
     */
    @Override
    public List<BalanceRefill> selectBalanceRefillList(BalanceRefill balanceRefill) {
        return balanceRefillMapper.selectBalanceRefillList(balanceRefill);
    }

    /**
     * 新增余额充值
     *
     * @param balanceRefill 余额充值
     * @return 结果
     */
    @Override
    public int insertBalanceRefill(BalanceRefill balanceRefill) {
        balanceRefill.setId(IdUtils.simpleUUID());
        balanceRefill.setCreateTime(DateUtils.getNowDate());
        balanceRefill.setBalanceOdd(this.getNo(FeeConstants.Balance_key));
        balanceRefill.setReceiptsMoney(NumberArithmeticUtils.safeSubtract(balanceRefill.getRechargeMoney(), balanceRefill.getDerateMoney()));
        this.setUnitInfo(balanceRefill);


        if (balanceRefill.getStatus().equals("10002")) {
            RoomBalance roomBalance = new RoomBalance();
            roomBalance.setRoomId(balanceRefill.getRoomId());
            roomBalance.setChargeId(balanceRefill.getChargeId());
            RoomBalance roomBalance1 = roomBalanceService.selectRoomBalance(roomBalance);
            if (roomBalance1 == null) {
                roomBalance.setReceiptsMoney(balanceRefill.getReceiptsMoney());

                Room room = roomService.selectRoomById(balanceRefill.getRoomId());
                roomBalance.setAncestors(room.getAncestors() + "," + balanceRefill.getRoomId());
                roomBalance.setDeptId(room.getDeptId());
                roomBalanceService.insertRoomBalance(roomBalance);
            } else {
                roomBalance1.setReceiptsMoney(NumberArithmeticUtils.safeAdd(roomBalance1.getReceiptsMoney(), balanceRefill.getRechargeMoney()));

                Room parentBean = roomService.selectRoomById(balanceRefill.getRoomId());
                roomBalance1.setAncestors(parentBean.getAncestors() + "," + balanceRefill.getRoomId());
                roomBalance1.setDeptId(parentBean.getDeptId());
                roomBalanceService.updateRoomBalance(roomBalance1);
            }
        }

        return balanceRefillMapper.insertBalanceRefill(balanceRefill);
    }

    /**
     * 修改余额充值
     *
     * @param balanceRefill 余额充值
     * @return 结果
     */
    @Override
    public int updateBalanceRefill(BalanceRefill balanceRefill) {
        balanceRefill.setUpdateBy(SecurityUtils.getUsername());
        balanceRefill.setUpdateTime(DateUtils.getNowDate());
        balanceRefill.setReceiptsMoney(NumberArithmeticUtils.safeSubtract(balanceRefill.getRechargeMoney(), balanceRefill.getDerateMoney()));

        if (balanceRefill.getStatus().equals("10002")) {
            RoomBalance roomBalance = new RoomBalance();
            roomBalance.setRoomId(balanceRefill.getRoomId());
            roomBalance.setChargeId(balanceRefill.getChargeId());
            RoomBalance roomBalance1 = roomBalanceService.selectRoomBalance(roomBalance);
            if (roomBalance1 == null) {
                roomBalance.setReceiptsMoney(balanceRefill.getReceiptsMoney());

                Room room = roomService.selectRoomById(balanceRefill.getRoomId());
                roomBalance.setAncestors(room.getAncestors() + "," + balanceRefill.getRoomId());
                roomBalance.setDeptId(room.getDeptId());
                roomBalanceService.insertRoomBalance(roomBalance);

            } else {
                roomBalance1.setReceiptsMoney(NumberArithmeticUtils.safeAdd(roomBalance1.getReceiptsMoney(), balanceRefill.getRechargeMoney()));


                Room parentBean = roomService.selectRoomById(balanceRefill.getRoomId());
                roomBalance1.setAncestors(parentBean.getAncestors() + "," + balanceRefill.getRoomId());
                roomBalance1.setDeptId(parentBean.getDeptId());
                roomBalanceService.updateRoomBalance(roomBalance1);
            }
        }
        this.setUnitInfo(balanceRefill);
        return balanceRefillMapper.updateBalanceRefill(balanceRefill);
    }

    /**
     * 批量删除余额充值
     *
     * @param ids 需要删除的余额充值ID
     * @return 结果
     */
    @Override
    public int deleteBalanceRefillByIds(String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            orgTreeService.deleteOrgTreeById(ids[i]);
        }

        return balanceRefillMapper.deleteBalanceRefillByIds(ids);
    }

    /**
     * 删除余额充值信息
     *
     * @param id 余额充值ID
     * @return 结果
     */
    @Override
    public int deleteBalanceRefillById(String id) {
        orgTreeService.deleteOrgTreeById(id);
        return balanceRefillMapper.deleteBalanceRefillById(id);
    }

    @Override
    public boolean addBalanceRefillByWx(PayBalanceRefillVo payBalanceRefillVo) {
        JSONObject json = JSONUtil.parseObj(payBalanceRefillVo.getParameterList());
        Room room = roomService.selectRoomById(json.getStr("roomId"));
        if (room == null) {
            return false;
        }
        String phoneNum = MiniContextUtils.getPhoneNum();
        switch (payBalanceRefillVo.getIndex()) {
            case 1: //余额充值
                //获取客户信息
                CustomInfo customInfo = customInfoService.getWxUserCustomInfo(room.getCommunityId(), phoneNum);
                if (customInfo == null) {
                    return false;
                }
                BalanceRefill balanceRefill = new BalanceRefill();
                BeanUtils.copyProperties(room, balanceRefill);
                BeanUtils.copyProperties(customInfo, balanceRefill);
                BeanUtils.copyProperties(payBalanceRefillVo, balanceRefill);
                balanceRefill.setChargeId(json.getStr("chargeId"));
                balanceRefill.setReceiptsMoney(balanceRefill.getRechargeMoney());
                this.insertBalanceRefill(balanceRefill);
                break;

            case 2: //在线支付
                BillPaymentVo billPaymentVo = new BillPaymentVo();
                billPaymentVo.setPaymentTime(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", payBalanceRefillVo.getPayeeTime()));
                billPaymentVo.setRoomId(payBalanceRefillVo.getRoomId());
                billPaymentVo.setPayMoney(payBalanceRefillVo.getRechargeMoney());
                billPaymentVo.setOrderNo(payBalanceRefillVo.getOrderNo());
                billPaymentVo.setSerialNo(StringUtils.getCode("SerialNo"));
                billPaymentVo.setRemark(payBalanceRefillVo.getOrderIntroduce());
                billPaymentVo.setRoom(room);
                JSONArray arr = json.getJSONArray("costIds");
                billPaymentVo.setBillVos(arr.stream().map(a -> {
                    BillVo billVo = new BillVo();
                    billVo.setCostIds(JSONUtil.parseArray(a.toString()).toList(String.class));
                    return billVo;
                }).collect(Collectors.toList()));
                wxPayfeeService.payment(billPaymentVo);
                break;
        }
        return true;
    }

    /**
     * 批量新增余额充值信息
     *
     * @param balanceRefills 余额充值对象
     */
    public int batchAddData(List<BalanceRefill> balanceRefills) {
        return balanceRefillMapper.batchAddData(balanceRefills);
    }

    public String getNo(String key) {
        int nextVal = SerialNumUtil.getInstance().nextInt(key);
        return key + NumberUtils.frontCompWithZore(nextVal, 7);
    }

    private void setUnitInfo(BalanceRefill bean) {
        Room parentBean = roomService.selectRoomById(bean.getRoomId());
        bean.setAncestors(parentBean.getAncestors() + "," + bean.getRoomId());
        bean.setDeptId(parentBean.getDeptId());
        orgTreeService.insertOrgTree(bean.getId(), bean.getBalanceOdd(), bean.getRoomId(), OrgConstants.balance, parentBean.getAncestors());
    }


}
